from fastapi import FastAPI
from afast_core.core_libs.mq.rabbit.rabbit_with_lock import RabbitMQClintWithLock
from afast_core.core_plugins.pluginbase import IBasePlugin as BasePlugin
from pydantic import BaseSettings as Settings



class RabbitMQClintWithLockPluginClient(RabbitMQClintWithLock, BasePlugin):
    '''
    使用示例：
    RabbitMQClintWithLockPluginClient(core_app=core_app, configs=RabbitMQClintWithLockPluginClient.RabbitMQSettings(
    host='127.0.0.1', port=6379
    ))
    '''
    # 设置插件默认的参数信息
    name = 'RabbitMQClintWithLock'

    def __init__(self, *, app: FastAPI = None, name=None, settings=None, startup_callback, **options):
        """创建应用的插件"""
        super().__init__(app=app, name=name, settings=settings, **options)
        self.startup_callback = startup_callback

    class RabbitMQSettings(Settings):
        RABBIT_HOST: str
        RABBIT_PORT: str
        VIRTUAL_HOST: str

    def setup(self, app: FastAPI, name: str = None, *args, **kwargs):
        """插件初始化"""
        self.app = app

        @app.on_event("startup")
        def startup_event():
            self._sync_rabbit = self.init_sync_rabbit(setting=self.settings)
            app.sync_rabbit = self._sync_rabbit
            if self.startup_callback:
                self.startup_callback()

        @app.on_event("shutdown")
        def shutdown_event():
            self._clear_all()
